package util.concurrent;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 7/14/2022 8:11 PM
 */
public class ReentrantLockTest {

    private static final Logger logger = LoggerFactory.getLogger(ReentrantLock.class);

    @Test
    public void test1() throws InterruptedException {
        // 创建锁对象
        ReentrantLock lock = new ReentrantLock();
        for (int i = 0; i < 3; i++) {
            new Thread(new ReentrantLockThread(lock), "线程" + i).start();
        }
        Thread.sleep(15000);
    }

    static class ReentrantLockThread implements Runnable {

        private final ReentrantLock lock;

        public ReentrantLockThread(ReentrantLock lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            try {
                //  获取锁
                lock.lock();
                logger.info("lock threadName {}", Thread.currentThread().getName());
                Thread.sleep(5000);
                logger.info("unlock threadName {}", Thread.currentThread().getName());
                // 释放锁
                lock.unlock();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}
